<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('Alohacart')) return;
/**
 * Aloha Cart
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage alohacart
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */

/**
 *  Class that represents shopping Cart
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com) 
 */
class Alohacart {
    /**
     * Session variable for the Cart
     * Data is stored in format: id_article=>quantity
     */
    private $_session_data;
    
    /**
     *  EcataloguE ProductModel
     */
    private $product_mdl;
	
	/**
	 *  EcataloguE CurrencyModel
	 */
	private $currency_mdl;
    
    /**
     * CompositeArticleModel
     */
    private $composite_article_mdl;
    
    /**
	 * Session variable for the composite products
     * Data is stored in format: id_composite=>array(id_article1=>quantity1,id_article2=>quantity2,...)
	 */
	private $session_data_composite;
    
    public function __construct() {        
        // We'll use standart PHP session. But in future we can change it to SPIP session        
        @session_start();        
        if (!isset($_SESSION["alohacart"]) || !is_array($_SESSION["alohacart"])) {
      		$_SESSION["alohacart"] = array();
    	}
        $this->_session_data = &$_SESSION["alohacart"];
        
        if (!isset($_SESSION["alohacart_composite"]) || !is_array($_SESSION["alohacart_composite"])) {
      		$_SESSION["alohacart_composite"] = array();
    	}
        $this->session_data_composite = &$_SESSION["alohacart_composite"];
        
        $this->product_mdl = pdk_load_class('ProductModel','classes');
		$this->currency_mdl = pdk_load_class('CurrencyModel','classes');
        $this->composite_article_mdl = pdk_load_class('CompositeArticleModel','classes');
    }
    
    /**
     *  Get array of products IDs that are located in the Cart 
     */
    public function GetProductsIDs() {
        return array_keys($this->_session_data);
    }
    
    /**
     *  Get array of products (quantities actually) that are located in the Cart 
     */
    public function GetProducts() {
        return $this->_session_data;
    }
    
    /**
     *  Gets quantity of given product in the cart
     *  If no such product in the cart, 0 will be returned
     */
    public function GetProduct($id_article) {
        return isset($this->_session_data[$id_article])?$this->_session_data[$id_article]:0;
    }
    
    /**
     *  Gets products total prices array in format: array(id_article1=>total_price1, id_article2=>total_price2)
	 *  in current currency 
     */
    public function GetProductsTotals() {
        $totals = array();
        $products = $this->GetProducts();         
        foreach ($products as $id_article=>$quantity) {
            $price = $this->product_mdl->GetProductPrice($id_article, $this->currency_mdl->GetCurrentCurrencyCode());
            $totals[$id_article] = $price*$quantity;
        }
        return $totals;
    }
    
    /**
     *  Remove all products from the Cart
     */
    public function ClearCart() {
		$this->_session_data = array();
  	}
    
    /**
     *  Count all products in the Cart
     *  @return Number of products in the Cart
     */
    public function CountProducts() {
		$cart_num = 0;
        foreach ($this->_session_data as $id_article=>$quantity) {
            $cart_num += $quantity;
        }
        return $cart_num;         
	}
    
    /**
     *  Count total price of products in the Cart in current currency
     *  NB: Price will be calculated according to product's currency rate
     *  @return Price of all products in the Cart
     */
    public function CountPrice() {
        // TODO: Когда в PDK будет возможность указывать какие поля селектить, то переделать сдесь на запрос с подсчетом. После переработки на GetProductPrice это под сомнением
		$cart_price = 0;
        
        foreach ($this->_session_data as $id_article=>$quantity) {
            $product_price = $this->product_mdl->GetProductPrice($id_article, $this->currency_mdl->GetCurrentCurrencyCode());
            $cart_price += $product_price*$quantity;
        }
        
        return $cart_price;         
	}
    
    /**
     *  Add product to cart
     */
    public function AddProduct($id_article, $quantity = 1) {
        if (!isset($this->_session_data[$id_article])) {
            $this->_session_data[$id_article] = $quantity;
	    } else {
	        $this->_session_data[$id_article] += $quantity;
	    }
        
        // Reset composite quantity modifications for this product
        unset($this->session_data_composite[$id_article]);
  	}
    
    /**
     *  Remove product from the Cart
     *  @param int $quantity How much products to remove
     */
    public function RemoveProduct($id_article, $quantity=false) {
        if (!$quantity)
            unset($this->_session_data[$id_article]);
        else if (isset($this->_session_data[$id_article])) {
            $this->_session_data[$id_article] -= $quantity;
            if ($this->_session_data[$id_article] <= 0)
                unset($this->_session_data[$id_article]); 
        }    
    }
    
    /**
     *  Update product in the cart
     */
    public function Updateproduct($id_article, $quantity) {
        $this->_session_data[$id_article] = $quantity;
        if ($this->_session_data[$id_article] <= 0)
            unset($this->_session_data[$id_article]);
            //$this->_session_data[$id_article] = 0;
    }
    
    /**
     *  Changes quantity of product that belongs to composite product
     *  @param int $id_composite ID of composite product
     *  @param int $id_article ID of product that belongs to composite
     *  @param int $quantity Quantity. Min=1, Max=Quantity that is set in composite product
     */
    public function UpdateCompositeProduct($id_composite, $id_article, $quantity) {
        $id_composite = intval($id_composite);
        $id_article = intval($id_article);
        $quantity = intval($quantity);
        if (!$id_composite || !$id_article) return false;
        
        if ($quantity < 1) $quantity = 1;
        
        $product = $this->GetProduct($id_composite);
        //if ($product)
          //  $quantity = $quantity * $product;
        
        $rows = $this->composite_article_mdl->select("id_composite=".$id_composite." AND id_article=".$id_article);
        if ($rows) {
            $row = $rows[0];
            if ($product)
                if ($quantity > $row['quantity']*$product) $quantity = $row['quantity']*$product;
            else
                if ($quantity > $row['quantity']) $quantity = $row['quantity'];
        }
        
        
         
        $this->session_data_composite[$id_composite][$id_article] = $quantity;
    }
    
    public function GetCompositeProduct($id_composite, $id_article) {
        //var_Dump($this->session_data_composite);
        return $this->session_data_composite[$id_composite][$id_article];
    }
} 
?>